package starter;

import mybatis.config.Configuration;
import mybatis.session.SqlSession;
import mybatis.session.SqlSessionFactory;
import server.request.HttpRequest;
import server.response.HttpResponse;
import spring.ApplicationContext;
import spring.utils.BeanUtils;
import springmvc.DispatchServlet;
import springmvc.config.WebConfig;

import java.io.File;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @author cg
 * @date 2023/6/21 15:33
 */
public class MyDispatchServlet extends DispatchServlet {
    @Override
    protected void doGet(HttpRequest request, HttpResponse response) {
        super.doGet(request, response);
    }

    @Override
    protected void doPost(HttpRequest request, HttpResponse response) {
        super.doPost(request, response);
    }

    @Override
    public void init(Class<?> config) throws Exception {
        ApplicationContext context = super.getContext();
        Configuration configuration = new Configuration("db.properties");
        SqlSessionFactory sqlSessionFactory = new SqlSessionFactory(configuration);
        SqlSession sqlSession = sqlSessionFactory.getSqlSession();
        context = new ApplicationContext(config);
        ConcurrentHashMap<String, Object> singletonObjects = context.getSingletonObjects();
        //解析MapperScan
        loadMapper(singletonObjects,config,sqlSession);
        context.refresh();
        //初始化mvc配置
        this.webConfig = new WebConfig("application.properties");
        //初始化springmvc的组件
        this.initStrategies(context);
    }

    private void loadMapper(ConcurrentHashMap<String, Object> singletonObjects, Class<?> config, SqlSession sqlSession) {
        MapperScan mapperScan = config.getAnnotation(MapperScan.class);
        String path = this.getClass().getResource("/").getPath();
        String realPath = path + (mapperScan.value().replaceAll("\\.", "/"));
        File dir = new File(realPath);
        //扫描所有的mapper
        doRegist(dir, singletonObjects, mapperScan.value(),sqlSession);
    }

    private void doRegist(File dir, ConcurrentHashMap<String, Object> singletonObjects, String path, SqlSession sqlSession) {
        for (File file : dir.listFiles()) {
            String fileName = file.getName();
            if (fileName.endsWith(".class")) {
                try {
                    fileName = fileName.substring(0, fileName.lastIndexOf("."));
                    Class<?> clazz = Class.forName(path + "." + fileName);
                    singletonObjects.put(BeanUtils.getDefaultBeanName(clazz), sqlSession.getMapper(clazz));
                } catch (ClassNotFoundException e) {
                    throw new RuntimeException(e);
                }
            }
        }
    }
}
